package com.heatup.apt.api.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.heatup.apt.api.controller.pay.util.MD5;
import com.heatup.apt.api.controller.pay.util.PropertiesUtil;
import com.heatup.apt.api.service.CouponService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.heatup.apt.api.controller.pay.util.Sha1Util;
import com.heatup.apt.api.service.CoreService;
import com.heatup.apt.common.dao.ChannerDetailedMapper;
import com.heatup.apt.common.dao.ChannerQrcodeMapper;


/**
 * 用户发给公众号的消息以及开发者需要的事件推送，将被微信转发到该控制器中
 * 
 * @author jixiangyun 2016年11月18日 下午12:03:19
 */
@Controller
@RequestMapping("/weChat_msg")
public class WeChatMsgBackController {
	private static final Logger logger = LoggerFactory.getLogger(WeChatMsgBackController.class);
	private String token = String.valueOf(PropertiesUtil.get("wechat_token")).trim();//"myd2016MYDreleasemyd";

	@Autowired
	private CoreService coreService;
	
	@Autowired
	private ChannerDetailedMapper channerDetailedMapper;
	@Autowired
	private ChannerQrcodeMapper channerQrcodeMapper;
	@Autowired
	private CouponService couponService;
	

	@ResponseBody
	@RequestMapping("/event_msg")
	public String weChatMsg(HttpServletRequest request, HttpServletResponse response) {

		return null;
	}

	@ResponseBody
	@RequestMapping("/wechat_token")
	public void getweChatToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		logger.info("===========================================进入微信统一微信消息调用接口 查看请求类型 mode is get or post :" + isGet);
		if (isGet) {
			logger.info("==============================微信验证token开始=========================================================");
			// 微信加密签名
			String signature = request.getParameter("signature");
			// 随机字符串
			String echostr = request.getParameter("echostr");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			String[] str = { token, timestamp, nonce };
			Arrays.sort(str); // 字典序排序
			String bigStr = str[0] + str[1] + str[2];
			logger.info("===========================================signature:" + signature + "=echostr:" + echostr + "====timestamp:" + timestamp + "========================================");
			// SHA1加密
			logger.info("===========================================微信验证token============str:" + Arrays.toString(str));
			String digest = MD5.getMessageDigest(bigStr.getBytes()).toLowerCase();
			String digest1 = Sha1Util.getSha1(bigStr);
			logger.info("===========================================微信验证token============digest:" + digest
					+ "====digest1:" + digest1 + "=========================================");
			// 确认请求来至微信
			if (digest.equals(signature)) {
				try {
					response.getWriter().print(echostr);
					logger.info("===========================================微信验证token成功=============================================");
				} catch (IOException e) {
					e.printStackTrace();
					logger.error(e.toString() + e.getCause());
				}
			} else if (digest1.equals(signature)) {
				response.getWriter().print(echostr);
				logger.info(
						"===========================================微信验证token成功=============================================");
			} else {
				logger.info(
						"===========================================微信验证token失败=============================================");
			}
		} else {
			PrintWriter out = response.getWriter();
			try {
				String msg = coreService.processRequest(request,response);
				logger.info("================================msg:"+msg+"=========================================");
				out.print(msg);
			} catch (Exception e) {
				logger.info("================================异常处理=========================================");
				out.print("欢迎关注了檬运动");
				e.printStackTrace();
				logger.error(e.toString() + e.getCause());
			}finally{
				out.close();
			}
		}
	}
	
	@ResponseBody
	@RequestMapping("/event_test")
	public String testInsert(HttpServletRequest request, HttpServletResponse response) {
		
		String msg = coreService.testInsert();
		return msg;
	}

}
